using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

namespace MVCFramework
{
    public class ModelCollection<T> : Collection<T>   where T :class  //, IModelDataCollection 
    {
        public event EventHandler<ModelChangedEventArgs<T>> Changed;

        protected override void InsertItem(int index, T newItem)
        {
            base.InsertItem(index, newItem);

            EventHandler<ModelChangedEventArgs<T>> temp = Changed;
            if (temp != null)
            {
                temp(this, new ModelChangedEventArgs<T>(
                    ChangeType.Added, newItem, null));
            }
        }
        protected override void SetItem(int index, T newItem)
        {
            T replaced = Items[index];
            base.SetItem(index, newItem);

            EventHandler<ModelChangedEventArgs<T>> temp = Changed;
            if (temp != null)
            {
                temp(this, new ModelChangedEventArgs<T>(
                    ChangeType.Replaced, replaced, newItem));
            }
        }
        protected override void RemoveItem(int index)
        {
            T removedItem = Items[index];
            base.RemoveItem(index);

            EventHandler<ModelChangedEventArgs<T>> temp = Changed;
            if (temp != null)
            {
                temp(this, new ModelChangedEventArgs<T>(
                    ChangeType.Removed, removedItem, null));
            }
        }
        protected override void ClearItems()
        {

            base.ClearItems();

            EventHandler<ModelChangedEventArgs<T>> temp = Changed;
            if (temp != null)
            {
                temp(this, new ModelChangedEventArgs<T>(
                    ChangeType.Cleared, null,null ));
            }
        }
    }

    public class ModelChangedEventArgs<T> : EventArgs
    {
        public readonly T ChangedItem;
        public readonly ChangeType ChangeType;
        public readonly T ReplacedWith;

        public ModelChangedEventArgs(ChangeType change, T item,
            T replacement)
        {
            ChangeType = change;
            ChangedItem = item;
            ReplacedWith = replacement;

        }

    }
    public enum ChangeType
    {
        Added,
        Removed,
        Replaced,
        Cleared,
    }

    public class ModelDataCollection : ModelCollection<IModelData>
    {
    }
}
